package com.atguigu.netty.buf;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import java.nio.charset.Charset;

/**
 * 用Unpooled.copiedBuffer(CharSequence string, Charset charset)创建ByteBuf
 * @author: 叶子
 * @date: 2022/02/17 19:39
 **/
public class NettyByteBuf02 {
    public static void main(String[] args) {
//      创建ByteBuf
        ByteBuf byteBuf = Unpooled.copiedBuffer("hello,world!", Charset.forName("utf-8"));
        if (byteBuf.hasArray()){
            byte[] content = byteBuf.array();
//            将content转成字符串
            System.out.println(new String(content,Charset.forName("utf-8")));
            System.out.println("byteBuf ="+byteBuf);//capacity =36 为字符串长度的3倍
        }
        System.out.println(byteBuf.getByte(0));//根据索引获取，不会导致刻度字节数发生变化
        int len = byteBuf.readableBytes();//可读取的字节数
        System.out.println("len ="+ len);
    //使用for取出各个字节
        for (int i = 0; i < len; i++) {
            System.out.println((char) byteBuf.getByte(i));
        }
        System.out.println(byteBuf.getCharSequence(0,4,Charset.forName("utf-8")));//hell
//        从索引位置0开始，读取4个字节，所以为hell
    }
}